package com.itheima.intercepter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.constant.UserConstant;
import com.itheima.exception.BizException;
import com.itheima.pojo.Result;
import com.itheima.pojo.User;
import com.itheima.utils.JwtUtil;
import com.itheima.utils.ThreadLocalUtil;
import io.netty.handler.codec.compression.Bzip2Decoder;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Slf4j
public class AuthInterceptor implements HandlerInterceptor {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    private StringRedisTemplate stringRedisTemplate;

    public AuthInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {

            log.info("请求路径:{}",request.getRequestURI());

            // 放行预检请求
            if ("OPTIONS".equals(request.getMethod())) {
                return true; // 放行 OPTIONS 请求
            }
            String token = request.getHeader("Authorization");
            if (null == token){
                throw new BizException("未登录");
            }

            Map<String, Object> stringObjectMap = JwtUtil.parseToken(token);
            String redisToken = stringRedisTemplate.opsForValue().get(UserConstant.LOGIN_PREFIX + stringObjectMap.get("id"));
            if (!StringUtils.hasLength(redisToken)){
                throw new BizException("登录失效");
            }
            if ( !redisToken.equals(token)) {
                 throw new BizException("登录失效");
            }

            User user = objectMapper.convertValue(stringObjectMap, User.class);
            //存入ThreadLocal中
            ThreadLocalUtil.set(user);
        } catch (Exception e) {
            log.info("登录失败",e);
            response.setStatus(401);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(objectMapper.writeValueAsString(Result.error(e.getMessage())));
            return false;
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清空ThreadLocal，避免内存泄漏
        ThreadLocalUtil.remove();
    }
}
